package com.itheima.ydd.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.ydd.common.PageResult;
import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.entity.Link;
import com.itheima.ydd.service.LinkService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/ydd_link")
@Slf4j
public class LinkController {

    @Autowired
    private LinkService linkService;

    @GetMapping("/rowInfo")
    public ResultData rowInfo(Long id) {
        LambdaQueryWrapper<Link> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Link::getId, id);
        Link link = linkService.getOne(queryWrapper);
        return ResultData.ok("", link);
    }

    @PostMapping("/update")
    public ResultData update(@RequestBody Link link) {
        LambdaQueryWrapper<Link> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Link::getId, link.getId());
        Link link1 = linkService.getOne(queryWrapper);
        link1.setDes(link.getDes());
        link1.setImg(link.getImg());
        link1.setTitle(link.getTitle());
        link.setType(link.getType());
        link1.setUrl(link.getUrl());
        linkService.update(link1, queryWrapper);
        return ResultData.ok("成功", null);
    }

    @GetMapping("/del")
    public ResultData delete(Long id) {
        LambdaUpdateWrapper<Link> lqw = new LambdaUpdateWrapper<>();
        lqw.eq(Link::getId, id);
        lqw.set(Link::getDefaultData, "0");
        linkService.update(lqw);
        return ResultData.ok("成功", null);
    }

    @PostMapping("/add")
    public ResultData add(@RequestBody Link link) {
        link.setDefaultData("1");
        linkService.save(link);
        return ResultData.ok("成功", null);
    }

    @GetMapping("list")
    public ResultData list(int type, Long page, Long limit) {

        Page<Link> pageInfo = new Page<>(page, limit);
        LambdaQueryWrapper<Link> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Link::getType, type);
        Page<Link> linkPage = linkService.page(pageInfo, queryWrapper);
        List<Link> records = linkPage.getRecords();
        Long count = Long.valueOf(linkService.count(queryWrapper));
        return ResultData.ok("", PageResult.init(count, page, limit, records));
    }
}
